package xyz.jcat.webmvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import xyz.jcat.common.exception.BusinessException;
import xyz.jcat.common.util.StringUtils;
import xyz.jcat.common.web.*;

import javax.validation.ConstraintViolationException;

@Slf4j
@ResponseBody
@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler(ParameterErrorException.class)
    public Resp parameterErrorExceptionHandler(ParameterErrorException e) {
        return requestParamsError(e.getErrors());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Resp httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        log.info("参数异常", e);
        return requestParamsError();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Resp methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            return requestParamsError(MethodParameterValidateUtils.convert(bindingResult.getFieldErrors()));
        }
        return requestParamsError();
    }

    private Resp requestParamsError() {
        return requestParamsError(null);
    }

    private Resp requestParamsError(Object data) {
        return Resp.fail(RespCodeMsg.REQUEST_PARAMETER_ERROR, data);
    }

    /**
     * 方法参数注解校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Resp constraintViolationExceptionHandler(ConstraintViolationException e) {
        return requestParamsError(MethodParameterValidateUtils.convert(e.getConstraintViolations()));
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Resp methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
        ParameterErrorVo error = new ParameterErrorVo(e.getName(), "参数错误");
        return requestParamsError(error);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Resp methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
        return Resp.fail(RespCodeMsg.METHOD_NOT_SUPPORTED);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Resp noHandlerFoundExceptionHandler(NoHandlerFoundException e) {
        return Resp.fail(RespCodeMsg.NOT_FOUND);
    }

    @ExceptionHandler(MissingRequestHeaderException.class)
    public Resp missingRequestHeaderExceptionHandler(MissingRequestHeaderException e) {
        return Resp.fail(RespCodeMsg.REQUEST_PARAMETER_ERROR, "缺少请求头："+e.getHeaderName());
    }

    @ExceptionHandler(RespException.class)
    public Resp respServiceExceptionHandler(RespException e) {
        Resp resp = e.getResp();
        if(resp != null) {
            return resp;
        }
        IRespCodeMsg respCodeMsg = e.getRespCodeMsg();
        String errorMsg = e.getErrorMsg();
        if(StringUtils.isNotEmpty(errorMsg)) {
            return Resp.fail(respCodeMsg, errorMsg);
        }
        return Resp.fail(respCodeMsg);
    }

    @ExceptionHandler(BusinessException.class)
    public Resp businessExceptionHandler(BusinessException e) {
        return Resp.fail(e.getMessage());
    }

    /**
     * 其他未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Resp defaultExceptionHandler(Exception e) {
        log.error("[UnKnown Error] -> {}", e.getMessage(), e);
        if(e instanceof BusinessException) {
            return Resp.fail(e.getMessage());
        }
        if(e instanceof RespException) {
            return Resp.fail(((RespException)e).getRespCodeMsg());
        }
        return Resp.fail(RespCodeMsg.SYSTEM_ERROR);
    }
}
